var fs = require('fs');
var myArgs = process.argv.slice(1);


var content = fs.readFileSync(myArgs[1], 'utf8');
 
var nbrContact = 0;
var contact = [];
var nom = [];
var tel = [];
var adresse = [];


for ( var i = 1; i <= content.length; i++){
    var fin = content.indexOf("END:VCARD")+9;
    contact[i] = content.substring(0, fin);
    content = content.replace(contact[i], "");
    nbrContact++;
	
	console.log(contact[i]);
}

for (i = 1; i <= nbrContact; i++){
    posNom = contact[i].indexOf("FN:") + 3;
    posFinNom = contact[i].indexOf("TEL;") - 1;
    nom[i] = contact[i].substring(posNom, posFinNom);
    
    posTel1 = contact[i].indexOf("CELL:") + 5;
    posTel1Fin = contact[i].indexOf("EMAIL") - 1;
    tel[i] = contact[i].substring(posTel1, posTel1Fin);
    tel[i] = tel[i].replace("HOME:","");
    tel[i] = tel[i].replace("PREF:","");
    
    posAdresse = contact[i].indexOf("EMAIL") + 6;
    posAdresseFin = contact[i].indexOf("END:VCARD") - 1;
    
    adresse[i] = contact[i].substring(posAdresse, posAdresseFin);
    adresse[i] = adresse[i].replace("HOME:","");
    adresse[i] = adresse[i].replace("PREF:","");
	
	//console.log(nom[i]);
	//console.log(adresse[i]);
	//console.log(tel[i]);
    
}


for (i = 1 ; i <= nbrContact; i++){
    for ( j = i+1 ; j <= nbrContact ; j++){
        if ((tel[i] == tel[j]) && (adresse[i] == adresse[j]) ){
                contact[j] = "";
        }
    }
}

var listContact = "";

for (i = 1 ; i <= nbrContact; i++) {
    listContact += contact[i];
}


fs.writeFile( myArgs[1], listContact , function (err) {
  if (err) throw err;
  console.log('It\'s saved! Ce merveilleux travail digne des plus grands codeurs a ete realiser par LOUIS KLEIJN (partie a supprimer lors du test :)   )');
});

